import {
  ActionType,
  PageContainer,
  ProBreadcrumb,
  ProFormInstance,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Divider, message,Input, Breadcrumb } from 'antd';
import React, { useRef, useState } from 'react';
import CreateForm from './components/CreateForm';
import { addDb, connectivityTest, delDb, getData, updateDb, updateStatus } from '@/services';
import './index.less'
import svg from '@/assets/三角.svg'
import { Link } from 'react-router-dom';
interface conncetTestInter {
  dbConnection?:string
  dbDriver?:string
  userName?:string
  password?:string
}
interface pageInter{
  current:number
  pageSize:number
  totalCount:number
}
const TableList: React.FC<unknown> = () => {
  const title = useRef<string>('')
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const formRef = useRef<ProFormInstance>()
  const [pageData,setPageData] = useState<pageInter>({} as pageInter)
  const actionRef = useRef<ActionType>();
  const columns:any = [
    {
      title: '数据源名称',
      dataIndex: 'dbName',
      valueType:'text',
      order:1.2,
      formItemProps:{
        rules:[
          {
            min:2
          },
          {
            max:20,
          }
        ]
      }
    },
    {
      title: '数据库类型',
      dataIndex: 'dbStyle',
      valueType: 'text',
      hideInSearch:true,
      initialValue:'Mysql',
      order:2,
      formItemProps: {
        rules: [
          { 
            required: true,
            message: '此项为必填项',
          },
        ],
      },
      renderFormItem:(_:any,{formItemProps}:any,form:any)=>{
        return <Input disabled/>
      }
    },
    {
      title:'数据源描述',
      dataIndex:'dbDescribe',
      hideInSearch:true,
      order:1
    },
    {
      title:'驱动类名',
      dataIndex:'dbDriver',
      hideInTable:true,
      hideInSearch:true,
      formItemProps: {
        rules: [
          { 
            required: true,
            message: '此项为必填项',
          },
        ],
      }
    },
    {
      title:'连接信息',
      dataIndex:'dbConnection',
      hideInSearch:true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
      order:1,
      tooltip:'示例jdbc:mysql://172.16.23.33:3306/basic'
    },
    {
      title: '应用状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: { text: '未发布', status: 0 },
        1: { text: '已发布', status: 1 },
        2:{text:'已停用',status:2}
      },
      order:2
    },
    
    {
      title:'更新时间',
      dataIndex:'updateTime',
      valueType:'dateTime',
      sorter:true,
      hideInSearch:true,
      hideInForm:true,
    },
    {
      title:'用户名',
      dataIndex:'userName',
      hideInSearch:true,
      hideInTable:true,
      formItemProps:{
        rules:[
          {
            max:20
          }
        ]
      }
    },
    {
      title:'密码',
      dataIndex:'password',
      hideInSearch:true,
      hideInTable:true,
      valueType:'password',
      formItemProps:{
        rules:[
          {
            max:18
          }
        ]
      }
    },
    {
      title: '操作',
      dataIndex: 'option',
      align:'center',
      valueType: 'option',
      render: (_:any, record:any) => {
        let param = {
          dbConnection:record.dbConnection,
          dbDriver:record.dbDriver,
          userName:record.userName,
          password:record.password
        }
        //判断发布状态  动态渲染
        return <>
          <a onClick={()=>onConnectTest(param)}>连通测试</a>
          <Divider type="vertical" />
          <a onClick={
              async()=>{
                await updateStatus({id:record.id})
                actionRef.current?.reloadAndRest?.();
              }
            }>{record.status==0||record.status==2?'发布':'停用'}</a>
             <Divider type="vertical" />
          {record.status!=1?<a onClick={async()=>{
                handleModalVisible(true)
                formRef.current?.setFieldsValue(record)
                title.current='编辑数据库'
              }
            }>编辑</a>:''}
             <Divider type="vertical" />
          {record.status==0?<a onClick={async()=>{
              const {success} =await delDb({id:record.id,status:record.status,isDel:!record.isDel})
              if(success){
                message.success('删除成功')
                actionRef.current?.reloadAndRest?.();
              }
            }}>删除</a>:''
            }
        </>
      }
    },
  ]

  //连通测试
  const onConnectTest = async(param:conncetTestInter)=>{
    if(param.dbConnection!=''){
      const {success} = await connectivityTest(param)
      if(success){
        message.success('数据库连接成功')
      }
    }else{
      formRef.current?.validateFieldsReturnFormatValue?.().then(async(value:any)=>{
        let param = {
          dbConnection:value.dbConnection,
          dbDriver:value.dbDriver,
          userName:value.userName,
          password:value.password
        } 
        const {success} = await connectivityTest(param)
        if(success){
          message.success('数据库连接成功')
        }
      })
    }
  }
  return (
    <PageContainer

      header={{
        title: '数据库管理',  
      }}
    >
      <Button onClick={() => {handleModalVisible(true);formRef?.current?.resetFields();title.current='新增数据库'}} type='primary' style={{float:'right',marginBottom:10}}>新增数据源</Button>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        pagination={{
          defaultPageSize:10,
          pageSizeOptions:[10,20,50],
          current:pageData.current,
          pageSize:pageData.pageSize,
          showSizeChanger:true,
          showQuickJumper:true
        }}
        search={{
          labelWidth: 120,
        }}
        request={async (params,sorter, filter) => {
          const {updateTime} = sorter
          const { data, success } = await getData(
           {...params,isByTime:updateTime?updateTime:''}
          );
          return {
            data: data?.list || [],
            total:data?.totalCount,
            success,
          };
        }}
        options={false}
        columns={columns}

      />
      <CreateForm
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        title={title.current}

      >
        <ProTable
          onSubmit={async (value) => {
            const fromData = formRef.current?.getFieldsValue(true)
            if(fromData.id){
              //修改
              let param = {
                ...value,
                id:fromData.id
              }
              const {success} = await updateDb(param)
              if (success) {
                message.success('修改成功');
                handleModalVisible(false);
                actionRef.current?.reload();
                
              }
            }else{
               //新增
            const {success} = await addDb(value);
            if (success) {
              message.success('添加成功');
              handleModalVisible(false);
              actionRef.current?.reload();
            }
          }
          //  改变form表单按钮样式
          }}
          form={{submitter:{
            searchConfig: { 
              submitText: '确定',
              resetText: '取消'
            }
          }
        }}
       
          
          onReset={()=>handleModalVisible(false)}
          formRef={formRef}
          rowKey="id"
          type="form"
          columns={columns}
        />
        <Button onClick={()=>onConnectTest({dbConnection:''})} style={{position:'absolute',bottom:55}}>连通测试</Button>
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
